import React, { useEffect, useState } from "react"
import { getStorageManager } from '@/file_storage'
import { dataURItoBlob, ensureExtName } from '@/common/utils'
import LazyImage from "@/components/LazyImage"
import { CaptureScreenshotService } from '@/common/capture_screenshot'
import { randomName, getPageDpi, downloadByBlob } from '@/common/utils'
import { getPlayTab } from "@/ext/common/tab"
import { captureVisibleTabAsync, captureFullScreenAsync } from '@/ext/ext'
import Ext from "@/common/web_extension"

export default function ScreenshotList() {

    const [list, setList] = useState<any[]>([])

    // 获取列表
    const getScreenshotListAsync = async () => {
        const list = await getStorageManager().getScreenshotStorage().list()
        setList(list)
    }

    // 截屏
    const handleTakeScreenshotAsync = async () => {
        const tab: any = await getPlayTab()
        const dataUrl: any = await captureVisibleTabAsync(tab.windowId)
        await getStorageManager().getScreenshotStorage().overwrite(ensureExtName('.png', 'screen.png'), dataURItoBlob(dataUrl))
        getScreenshotListAsync()
    }

    //  截全屏
    const handleTakeFullScreenshotAsync = async () => {
        const tab: any = await getPlayTab()
        const dataUrl: any = await captureFullScreenAsync(tab.id)
        await getStorageManager().getScreenshotStorage().overwrite(ensureExtName('.png', 'full_screen.png'), dataURItoBlob(dataUrl))
        getScreenshotListAsync()
    }

    // 下载截图 通过createObjectURL
    const downloadScreenshotAsync = async (name: string, fullPath: string, byExt?: Boolean) => {
        if (byExt) {
            downloadByExt(name, fullPath)
        } else {
            const buffer: any = await getStorageManager().getScreenshotStorage().read(fullPath, 'ArrayBuffer')
            const blob = new Blob([new Uint8Array(buffer)]) // 转blob
            downloadByBlob(blob, name)
        }
    }

    // 测试：通过chrome.downloads.download下载图片
    const downloadByExt = (name: string, fullPath: string) => {
        getStorageManager().getScreenshotStorage().read(fullPath, 'DataURL').then((dataUrl: any) => {
            Ext.downloads.download({
                url: dataUrl,
                filename: name
            });
        })
    }

    // 选择截图
    const handleTakeSelectionScreenshot = async () => {
        const tab: any = await getPlayTab()
        // 给tab发送消息，去选择区域
        Ext.tabs.sendMessage(tab.id, {
            action: 'SELECT_SCREEN_AREA'
        }, {}, (response: any) => {
            // 收到响应值后，根据选择的区域信息去截图
            const { rect, devicePixelRatio } = response;
            const captureScreenshotService = new CaptureScreenshotService({
                captureVisibleTab: () => {
                    return captureVisibleTabAsync(tab.windowId, { format: 'png' }) as Promise<any>
                }
            });
            captureScreenshotService
                .captureScreenInSelectionSimple(tab.id, {
                    rect,
                    devicePixelRatio,
                }).then((dataUrl: any) => {
                    const fileName = `${randomName()}_dpi_${getPageDpi()}.png`;
                    getStorageManager()
                        .getScreenshotStorage()
                        .write(fileName, dataURItoBlob(dataUrl)).then(() => {
                            getScreenshotListAsync()
                        })
                })
        })
    }

    // 删除
    const deleteScreentshotAsync = async (name: string) => {
        await getStorageManager()
            .getScreenshotStorage().remove(name);
        getScreenshotListAsync();
    }

    // 清空
    const clearScreenshotsAsync = async () => {
        await getStorageManager().getScreenshotStorage().clear()
        getScreenshotListAsync();
    }

    // 请求数据
    useEffect(() => {
        getScreenshotListAsync()
    }, [])

    return <div className="screenshot-container">
        {/* <Space>
            <Button onClick={handleTakeScreenshotAsync}>视口区域截图</Button>
            <Button onClick={handleTakeFullScreenshotAsync}>滚动截全图</Button>
            <Button onClick={handleTakeSelectionScreenshot}>选择截图</Button>
            <Button onClick={clearScreenshotsAsync}>清空</Button>
        </Space> */}

        <ul className="screenshot-content">
            {
                list.map(item => {
                    return <li key={item.fullPath}
                        style={{
                            display: 'flex',
                            alignItems: 'center'
                        }}
                    >
                        <span className="timestamp">
                            {item.createTime && item.createTime.toLocaleString()} - <span className="filename">{decodeURIComponent(item.name)}</span>
                        </span>
                        <a
                            href="#"
                            onClick={e => {
                                e.preventDefault();
                                downloadScreenshotAsync(item.name, item.fullPath, false)
                            }}
                        >
                            <LazyImage fullName={item.name} storageType="screenshot" />
                        </a>
                        {/* <span>{item.name}</span> */}
                        {/* <Button onClick={() => downloadScreenshotAsync(item.name, item.fullPath, false)}>下载</Button>
                        <Button onClick={() => deleteScreentshotAsync(item.name)}>删除</Button> */}
                    </li>
                })
            }
        </ul>
    </div>
}